import store from '@/store'
import { EventBus } from '@/tools/bus'

export const webSocketManger = {
  data() {
    return {
      ws: null,
      wsUrl: '',
      isConnect: false,
      isReconnect: false,
      reconnectCount: 0,
      reconnectTime: 3000,
      reconnectMaxCount: 5,
      reconnectTimer: null,
    }
  },
  mounted() {
    fetch('/static/ipConfig.json')
        .then(res => res.json())
        .then(data => {
          this.wsUrl = data.wsbaseUrl
          this.connect()
        })
        .catch(err => {
          console.error('加载配置文件失败:', err)
        })
  },
  methods: {
    connect() {
      if (!this.wsUrl) return
      if (this.ws) {
        this.ws.close()
        this.ws = null
      }
      this.ws = new WebSocket(this.wsUrl)

      this.ws.onopen = () => {
        console.log('WebSocket 连接成功',this.ws)
        store.commit('setWebSocket', this.ws)
        EventBus.$emit('ws-connected')
        this.isConnect = true
        this.isReconnect = false
        this.reconnectCount = 0
        this.ws.sendMessage = (data) => {
          if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
            console.warn('WebSocket 未连接或连接已关闭，无法发送消息')
            return
          }
          const sendData = () => {
            let msg = ''
            if (typeof data === 'string') {
              msg = data
            } else {
              try {
                msg = JSON.stringify(data)
              } catch (e) {
                console.error('序列化失败', e)
                return
              }
            }
            this.ws.send(msg)
          }

          if (this.ws.readyState === WebSocket.OPEN) {
            sendData()
          } else if (this.ws.readyState === WebSocket.CONNECTING) {
            console.log('WebSocket 正在连接，延迟发送')
            setTimeout(() => {
              this.ws.sendMessage(data)
            }, 1000)
          } else {
            console.warn('WebSocket 未连接，尝试重新连接')
            this.connect()
          }
        }
        this.ws.sendMessage({"cmd":"getLoginUserInfo"})
        if (this.reconnectTimer) {
          clearTimeout(this.reconnectTimer)
          this.reconnectTimer = null
        }
      }

      this.ws.onmessage = (event) => {
        const data=JSON.parse(event.data)
        console.log('收到消息:', data)
        if (data.cmd==='getLoginUserInfo'){
          store.commit('setUserInfo',data.data)
        }
        else {
          EventBus.$emit('ws-message', data)
        }
      }

      this.ws.onerror = (error) => {
        console.error('WebSocket 错误', error)
      }

      this.ws.onclose = () => {
        console.log('WebSocket 连接关闭')
        this.isConnect = false
        store.commit('setWebSocket', null)
        EventBus.$emit('ws-close')

        if (!this.isReconnect && this.reconnectCount < this.reconnectMaxCount) {
          this.isReconnect = true
          this.reconnectTimer = setTimeout(() => {
            this.isReconnect = false
            this.reconnectCount++
            console.log(`第${this.reconnectCount}次重连`)
            this.connect()
          }, this.reconnectTime)
        }
      }
    },

    close() {
      if (this.ws) {
        this.ws.close()
      }
      if (this.reconnectTimer) {
        clearTimeout(this.reconnectTimer)
        this.reconnectTimer = null
      }
      this.isConnect = false
      this.isReconnect = false
      this.reconnectCount = 0
      store.commit('setWebSocket',null)
    }
  }
}
